// import type { Avatar } from '../types/avatar';

export interface Voice {
  voice_id: string;
  name: string;
  gender: string;
  language: string;
  language_code: string;
  preview_audio?: string;
  support_locale?: boolean;
  locales?: string[];
}

class PreviewService {
  private baseURL = '/api';

  // 使用浏览器 Web Speech API 估算视频时长（基于中文约150字/分钟，英文约180字/分钟）
  estimateVideoDuration(script: string, speed: number = 1.0): number {
    if (!script.trim()) return 0;

    // 检测是否包含中文字符
    const hasChinese = /[\u4e00-\u9fff]/.test(script);

    // 估算字符数（中文按字符计算，英文按单词计算）
    let charCount = 0;
    if (hasChinese) {
      // 中文：约150字/分钟
      charCount = script.length;
      const baseMinutes = charCount / 150;
      return (baseMinutes * 60) / speed; // 转换为秒并考虑语速
    } else {
      // 英文：约180单词/分钟
      const words = script.trim().split(/\s+/).length;
      const baseMinutes = words / 180;
      return (baseMinutes * 60) / speed; // 转换为秒并考虑语速
    }
  }

  // 获取 Avatar 的默认 voice 信息
  async getAvatarVoice(avatarId: string): Promise<{ voice_id?: string; voice_name?: string }> {
    try {
      const response = await fetch(`${this.baseURL}/avatars/${avatarId}/voice`, {
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        return {};
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to get avatar voice:', error);
      return {};
    }
  }

  // 获取语音列表
  async getVoices(): Promise<Voice[]> {
    try {
      const response = await fetch(`${this.baseURL}/voices`, {
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to get voices:', error);
      return [];
    }
  }
}

export default new PreviewService();
